package com.macro.mall.portal.controller;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.domain.MessageEnum;
import com.macro.mall.domain.MessageManagementAssemble;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.config.WebSocket;
import com.macro.mall.portal.service.MmsMessageService;
import com.macro.mall.portal.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Slf4j
@Controller
@Api(tags = "WebSocketController", description = "消息管理（http接口api）")
@RequestMapping("/websocket")
public class WebSocketController {
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private MmsMessageService mmsMessageService;
    @Autowired
    private WebSocket webSocket;

    /*@RequestMapping("/websocket/{name}")
    public String webSocket(@PathVariable String name, Model model) {
        try {
            log.info("跳转到websocket的页面上");
            model.addAttribute("username", name);
            return "websocket";
        } catch (Exception e) {
            log.info("跳转到websocket的页面上发生异常，异常信息是：" + e.getMessage());
            return "error";
        }
    }*/

    @ApiOperation(value = "消息写入", notes = "私信-留言")
    @ApiImplicitParams({
            @ApiImplicitParam(name="fromUsername", value="发送者username", required=true, paramType="query", dataType="String"),
            @ApiImplicitParam(name="toUsername", value="接收者username", required=true, paramType="query", dataType="String"),
            @ApiImplicitParam(name="msg", value="消息内容", required=true, paramType="query", dataType="String")
    })
    @RequestMapping(value = "/leave/word", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult leaveWord(@RequestParam String fromUsername ,@RequestParam String toUsername,  @RequestParam String msg) {
        UmsMember fromMember = memberService.getByUsername(fromUsername);
        UmsMember toMember = memberService.getByUsername(toUsername);
        if (null == fromMember || null == toMember)
            return CommonResult.failed("系统错误");
        if(0 == mmsMessageService.recordLeaveWord(fromMember.getId(), toMember.getId(), msg, MessageEnum.MSG_READ_STATUS_NO))
            return CommonResult.failed("I0异常");
        return CommonResult.success(1);
    }



    @ApiOperation(value = "获取XX的在线状态，0：表示离线，1：表示在线", notes = "在线状态查询")
    @ApiImplicitParam(name="username", value="username", required=true, paramType="query", dataType="String")
    @RequestMapping(value = "/get/on/line/status", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getOnLineStatus(@RequestParam String username) {
        UmsMember member = memberService.getByUsername(username);
        if (null == member)
            return CommonResult.failed();
        return CommonResult.success(member.getOnLineStatus());
    }

    @ApiOperation(value = "根据会员ID获取会员信息", notes = "根据会员ID获取username")
    @ApiImplicitParam(name="id", value="会员ID", required=true, paramType="query", dataType="long")
    @RequestMapping(value = "/get/username/by/id", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getUsernameById(@RequestParam long id) {
        UmsMember member = memberService.getById(id);
        if (null == member)
            return CommonResult.failed("获取会员信息失败");
        return CommonResult.success(member);
    }

    @ApiOperation(value = "和对方聊天记录查询  http接口，调该接口会更新对方的一个会话状态（已读）,并获取未读消息集合", notes = "点击消息列表中的单元，进入一对一聊天接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="selfId", value="我的会员Id", required=true, paramType="query", dataType="long"),
            @ApiImplicitParam(name="oppositeId", value="对方会员Id，若是系统消息，则传0即可", required=true, paramType="query", dataType="long")
    })
    @RequestMapping(value = "/into/one/on/one", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult intoOneOnOneSession(@RequestParam long selfId, @RequestParam long oppositeId) {
        List<MessageManagementAssemble> list = mmsMessageService.getUnreadMstList(selfId, oppositeId);
        return CommonResult.success(list);
    }

    @ApiOperation(value = "近期会话列表", notes = "近期会话列表，列表item结构：\n" +
            "{'oppositeId':'发送者memberId',  \n" +
            "'oppositeUsername':'oppositeUsername',  \n" +
            "'nickname':'发送者昵称',  \n" +
            "'icon':'发送者头像',  \n" +
            "'oppositeType':'发起者类型（0：普通会员，1：平台）',  \n" +
            "'count':'消息数量'" +
            "}")
    @ApiImplicitParam(name="username", value="username", required=true, paramType="query", dataType="String")
    @RequestMapping(value = "/get/session/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getSessionList(@RequestParam String username) {
        return CommonResult.success(mmsMessageService.getSessionList(username));
    }

    @ApiOperation(value = "历史记录（或者未展示的已读消息）", notes = "更多记录,每次传输currentPageIndex必须+1，每次展示数据30条")
    @ApiImplicitParams({
            @ApiImplicitParam(name="selfUsername", value="自己的账号", required=true, paramType="query", dataType="String"),
            @ApiImplicitParam(name="oppositeUsername", value="私信者的账号，0：代表平台消息，非0：代表普通私信", required=true, paramType="query", dataType="String"),
            @ApiImplicitParam(name="currentPageIndex", value="当前页数,更多记录默认+1", required=true, paramType="query", dataType="Integer")
    })
    @RequestMapping(value = "/get/more/history", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getMoreMsgOfHistory(@RequestParam String selfUsername ,@RequestParam String oppositeUsername,  @RequestParam Integer currentPageIndex) {

        List<MessageManagementAssemble> list = null;

        UmsMember selfMember = memberService.getByUsername(selfUsername);
        if (null == selfMember) {
            return CommonResult.failed("系统错误");
        }

        //判定是聊天信息还是平台通知消息
        if (StringUtils.equals("0", oppositeUsername)) {
            list = mmsMessageService.getMoreMsgOfHistory(selfMember, null, currentPageIndex);
        } else {
            UmsMember sfMember = memberService.getByUsername(oppositeUsername);
            if (null == sfMember) {
                return CommonResult.failed("系统错误");
            }
            list = mmsMessageService.getMoreMsgOfHistory(selfMember, sfMember, currentPageIndex);
        }
        return CommonResult.success(list);
    }



    @ApiOperation(value = "前端json字符串后台处理", notes = "前端json字符串后台处理")
    @ApiImplicitParam(name="str", value="str", required=true, paramType="query", dataType="String")
    @RequestMapping(value = "/str/to/json", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult strToJson(@RequestParam String str) {

        JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println(jsonObject);
        return CommonResult.success(jsonObject);
    }

}
